"""
进度对话框组件
"""

import tkinter as tk
from tkinter import ttk
from typing import Optional, Callable
import threading


class ProgressDialog:
    """进度对话框"""
    
    def __init__(self, parent, title: str = "处理中...", message: str = "请稍候..."):
        self.parent = parent
        self.title = title
        self.message = message
        self.window = None
        self.progress_var = None
        self.progress_bar = None
        self.message_label = None
        self.cancel_callback: Optional[Callable] = None
        self.is_cancelled = False
        
    def show(self, cancelable: bool = False):
        """显示进度对话框"""
        self.window = tk.Toplevel(self.parent)
        self.window.title(self.title)
        self.window.geometry("400x150")
        self.window.resizable(False, False)
        
        # 居中显示
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 创建组件
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 消息标签
        self.message_label = ttk.Label(main_frame, text=self.message)
        self.message_label.pack(pady=(0, 10))
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            main_frame,
            variable=self.progress_var,
            maximum=100,
            length=350
        )
        self.progress_bar.pack(pady=(0, 10))
        
        # 取消按钮
        if cancelable:
            cancel_btn = ttk.Button(
                main_frame,
                text="取消",
                command=self._on_cancel
            )
            cancel_btn.pack()
        
        # 居中窗口
        self._center_window()
        
        # 更新显示
        self.window.update()
    
    def _center_window(self):
        """居中窗口"""
        self.window.update_idletasks()
        
        # 获取窗口尺寸
        window_width = self.window.winfo_width()
        window_height = self.window.winfo_height()
        
        # 获取屏幕尺寸
        screen_width = self.window.winfo_screenwidth()
        screen_height = self.window.winfo_screenheight()
        
        # 计算居中位置
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        
        self.window.geometry(f"{window_width}x{window_height}+{x}+{y}")
    
    def update_progress(self, value: float, message: str = None):
        """更新进度"""
        if self.window and self.window.winfo_exists():
            self.progress_var.set(value)
            
            if message and self.message_label:
                self.message_label.config(text=message)
            
            self.window.update()
    
    def set_indeterminate(self, indeterminate: bool = True):
        """设置不确定进度模式"""
        if self.progress_bar:
            if indeterminate:
                self.progress_bar.config(mode='indeterminate')
                self.progress_bar.start()
            else:
                self.progress_bar.stop()
                self.progress_bar.config(mode='determinate')
    
    def set_cancel_callback(self, callback: Callable):
        """设置取消回调"""
        self.cancel_callback = callback
    
    def _on_cancel(self):
        """处理取消操作"""
        self.is_cancelled = True
        if self.cancel_callback:
            self.cancel_callback()
        self.close()
    
    def close(self):
        """关闭对话框"""
        if self.window and self.window.winfo_exists():
            self.window.destroy()
        self.window = None
    
    def is_open(self) -> bool:
        """检查对话框是否打开"""
        return self.window is not None and self.window.winfo_exists()


class TaskProgressDialog(ProgressDialog):
    """任务进度对话框（支持多任务显示）"""
    
    def __init__(self, parent, title: str = "任务处理中..."):
        super().__init__(parent, title)
        self.task_labels = []
        self.current_task = 0
        self.total_tasks = 0
    
    def show(self, total_tasks: int = 1, cancelable: bool = False):
        """显示任务进度对话框"""
        self.total_tasks = total_tasks
        
        self.window = tk.Toplevel(self.parent)
        self.window.title(self.title)
        self.window.geometry("450x200")
        self.window.resizable(False, False)
        
        # 居中显示
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 创建组件
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 总体进度标签
        self.overall_label = ttk.Label(main_frame, text=f"任务进度: 0 / {total_tasks}")
        self.overall_label.pack(pady=(0, 5))
        
        # 总体进度条
        self.overall_progress_var = tk.DoubleVar()
        self.overall_progress_bar = ttk.Progressbar(
            main_frame,
            variable=self.overall_progress_var,
            maximum=100,
            length=400
        )
        self.overall_progress_bar.pack(pady=(0, 10))
        
        # 当前任务标签
        self.current_task_label = ttk.Label(main_frame, text="准备开始...")
        self.current_task_label.pack(pady=(0, 5))
        
        # 当前任务进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            main_frame,
            variable=self.progress_var,
            maximum=100,
            length=400
        )
        self.progress_bar.pack(pady=(0, 10))
        
        # 取消按钮
        if cancelable:
            cancel_btn = ttk.Button(
                main_frame,
                text="取消",
                command=self._on_cancel
            )
            cancel_btn.pack()
        
        # 居中窗口
        self._center_window()
        self.window.update()
    
    def start_task(self, task_name: str):
        """开始新任务"""
        self.current_task += 1
        
        if self.window and self.window.winfo_exists():
            # 更新总体进度
            overall_progress = (self.current_task - 1) / self.total_tasks * 100
            self.overall_progress_var.set(overall_progress)
            self.overall_label.config(text=f"任务进度: {self.current_task - 1} / {self.total_tasks}")
            
            # 重置当前任务进度
            self.progress_var.set(0)
            self.current_task_label.config(text=f"正在处理: {task_name}")
            
            self.window.update()
    
    def complete_task(self):
        """完成当前任务"""
        if self.window and self.window.winfo_exists():
            # 设置当前任务为100%
            self.progress_var.set(100)
            
            # 更新总体进度
            overall_progress = self.current_task / self.total_tasks * 100
            self.overall_progress_var.set(overall_progress)
            self.overall_label.config(text=f"任务进度: {self.current_task} / {self.total_tasks}")
            
            self.window.update()
    
    def update_task_progress(self, value: float, message: str = None):
        """更新当前任务进度"""
        if self.window and self.window.winfo_exists():
            self.progress_var.set(value)
            
            if message:
                self.current_task_label.config(text=message)
            
            self.window.update()
